let express = require('express');
let router = express.Router();
let path = require('path');
let fs = require("fs");
let moment = require('moment');
let upload = multer({
    dest: 'upload/',
  });
let logDao = require('../../model/client/log.js')

//客户端上传log记录
/**
 * @api {post} /api/client/log/add  上传出入日志
 * @apiName 上传出入日志
 * @apiGroup log
 * @apiVersion 0.1.0 
 * @apiParam {String} serialNum  设备唯一编号 
 * @apiSuccess {String} status 状态码
 * @apiSuccess {Json} msg  信息
 */
router.post('/add' , upload.single('file'), function (req,res,next) {
    let serialNum = req.body.serialNum;
    let  getMessageBySerialNum  = await logDao.getMessageBySerialNum(serialNum);
    if(getMessageBySerialNum.length<=0){
        return await res.json({status:203,msg:'非法设备！'})
    }
    let  file =req.file;
    let  dirName='log';
 let type = file.mimetype.split('/')[1];
 let fileName = `${file.filename}.${type}`; // 文件重命名
 let date = new Date();
 let today = moment(date).format('YYYYMMDD');
 let filepath = path.join(__dirname + '/../../../upload/'+dirName+'/');
 //拼接文件名称
 let newFilePath = path.join(filepath, fileName);
 //上传文件
 fs.renameSync(file.path, newFilePath);
 let fileUrl ='/'+dirName+'/'+fileName;
    await logDao.addLog(getMessageBySerialNum[0].villageId,getMessageBySerialNum[0].buildingId,getMessageBySerialNum[0].unitId,fileUrl) 
 await res.json({status:200,msg:"success"})
})


module.exports =router;